package com.mac.macjetpackdemo.base

import androidx.lifecycle.ViewModel
import com.google.gson.JsonParseException
import com.mac.macjetpackdemo.data.model.BaseModel
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import java.net.UnknownHostException

open class BaseViewModel : ViewModel() {

    suspend fun <T> net(
        block: () -> Deferred<BaseModel<T> ?>,
        success: (result: T) -> Unit,
        failed: (String, String?) -> Unit
    ) {
        withContext(Dispatchers.IO) {
            try {
                val deferred = block()
                val model = deferred.await()
                model?.run {
                    if (code == "10000") {
                        success(result)
                    } else {
                        failed(code, msg)
                    }
                }
            } catch (e: Exception) {
                when (e) {
                    is HttpException -> {
                        failed(e.code().toString(), e.message())
                    }
                    is JsonParseException -> {
                        failed(11.toString(), e.message)
                    }
                    is UnknownHostException -> {
                        failed(12.toString(), "网络异常")
                    }
                    else -> failed(99.toString(), "请求失败")
                }
            }
        }
    }
}